package com.lywz.core.fileUpload.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.springframework.stereotype.Service;

import com.lywz.core.exception.ExceptionMes;
import com.lywz.core.exception.SSException;
import com.lywz.core.fileUpload.FileUploadProcessor;
import com.lywz.core.fileUpload.UploadFile;
import com.lywz.core.util.CommonUtil;
import com.lywz.core.util.ImageUtil;

/**
 * 默认文件上传 该实现不会对任何文件进行任何处理。 文件名，采用文件md5进行计算，如果从夫的图片，则会处于同一张图片。
 * 
 * @author Lionel pang
 * @date 2010-5-5
 * 
 */
@Service("defaultFileUpload")
public class DefaultFileUpload implements FileUploadProcessor {

    @Override
    public String uploadOneFile(final UploadFile file) throws SSException {
        List<String> list = uploadFile(file);
        
        return list == null || list.size() == 0? null: list.get(0);
    }
    
    @Override
    public List<String> uploadFile(final UploadFile... files) throws SSException {
        // 返回结果
        List<String> results = new ArrayList<String>();

        for (UploadFile file : files) {
            String dirpath = file.getPath();
            // 返回的网络映射名称
            String netPath = dirpath;

            dirpath = file.getBasePath() + dirpath;
            File dir = new File(dirpath);

            boolean mkdirSuccess = true;
            if (!dir.isDirectory()) {
                // 创建目录
                synchronized (DefaultFileUpload.class) {
                    if (!dir.isDirectory()) {
                        mkdirSuccess = dir.mkdirs();
                    }
                }
            }
            if (!mkdirSuccess) { // 如果创建目录失败，则直接返回空列表
                return Collections.emptyList();
            }

            // 获取源文件
            File src = file.getFile();
            // 通过md5值计算文件名称
            String fileName = CommonUtil.md5(src);
            netPath += fileName + "." + file.getFormate();

            StringBuffer targetFileName = new StringBuffer();
            targetFileName.append(dirpath).append(fileName).append(".").append(file.getFormate());

            // 目标文件
            File target = new File(targetFileName.toString());
            if (CommonUtil.copyFile(src, target)) {
                    // 如果为0，则直接不处理
                if(file.getWidth() != 0 && file.getWidth() != 0){
                    ImageUtil.getScaledImg(target, file.getWidth(), file.getWidth(), file.getFormate());
                }
            } else {
                throw SSException.get(ExceptionMes.SYSEXCEPTION);
            }
            // 添加到结果中
            results.add(netPath);
        }

        return results;
    }

}
